<template>
  <div>
    <div class="page-title" style="width: 100%">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <a @click="$router.go(-2)">接收任务列表</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <a @click="$router.go(-1)">执行任务</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>作业现场检查</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="page-content">
      <el-row>
        <el-form label-width="80px" :inline="true" :model="formData">
          <el-row>
            <el-col :span="6">
              <el-form-item label="检查人">
                <el-input
                  v-model="formData.execStaffName"
                  readonly
                  style="width: 200px"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检查日期">
                <el-date-picker
                  v-model="formData.checkDate"
                  style="width: 200px"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  :readonly="submitReadonly"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检查类别">
                <el-input
                  v-model="formData.checkType"
                  readonly
                  style="width: 200px"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="受检班组">
                <el-input
                  v-model="formData.taskItem"
                  readonly
                  style="width: 200px"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="受检单位">
                <el-cascader
                  placeholder="请选择受检单位"
                  style="width: 200px"
                  v-model="checkCompanyList1"
                  :options="checkCompanyNameOptions1"
                  clearable
                  filterable
                  ref="refHandle1"
                  :props="{
                    expandTrigger: 'hover',
                    checkStrictly: true,
                    value: 'nodeCode',
                    label: 'label',
                    children: 'children',
                  }"
                  :show-all-levels="true"
                  :disabled="submitReadonly"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检查地点">
                <el-input
                  v-model="formData.address"
                  style="width: 200px"
                  placeholder="请输入"
                  :readonly="submitReadonly"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="作业内容">
                <el-cascader
                  placeholder="请选择"
                  style="width: 200px"
                  v-model="checkContentsList"
                  :options="checkContentListOptions"
                  clearable
                  filterable
                  ref="refHandle2"
                  :props="{
                    expandTrigger: 'hover',
                    checkStrictly: true,
                    value: 'dictCode',
                    label: 'name',
                    children: 'childNodes',
                  }"
                  :show-all-levels="true"
                  :disabled="submitReadonly"
                ></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检查类型">
                <el-select
                  style="width: 200px"
                  v-model="formData.type"
                  placeholder="选择类型"
                  clearable
                >
                  <el-option
                    v-for="item in types"
                    :key="item.id"
                    :label="item.name"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="text-align: center">
              <el-button
                type="primary"
                style="margin-right: 20px"
                :disabled="submitReadonly"
                @click="generateChecklist"
                >生成检查单</el-button
              >
              <el-button type="danger" @click="cancel1">取消并返回</el-button>
            </el-col>
            <el-col :span="8">
              查询:<el-input
                placeholder="输入关键字查询"
                v-model="filterText"
                style="width: 80%; margin-left: 5px"
                @input="onFilterText"
              ></el-input>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <el-row
        style="
          padding-top: 5px;
          border-top: 2px dashed #dddddd;
          text-align: center;
        "
      >
        <el-col :span="16">
          <div v-if="this.checkItemOptions.length === 0">
            请选择上面各选项，生产检查单！
          </div>
          <el-tabs
            tab-position="left"
            v-else
            @tab-click="handleClickTab"
            v-loading="tableLoading"
          >
            <el-tab-pane
              v-for="item in checkItemOptions"
              :key="item.checkListItemName"
              :label="item.checkListItemName"
            >
              <el-table :data="item.childNodes" border max-height="400px">
                <el-table-column
                  prop="checkListItemName"
                  label="检查项"
                  align="center"
                ></el-table-column>
                <el-table-column label="现场执行" align="center" width="120px">
                  <template slot-scope="scope">
                    <!-- isProblem===false  ---  是现场执行
                    isProblem===true  ---  不是现场执行-->
                    <el-switch
                      v-model="scope.row.isProblem"
                      active-color="#ff4949"
                      inactive-color="#13ce66"
                      active-text="否"
                      inactive-text="是"
                    ></el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="150px">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      size="mini"
                      @click="addProblem(scope.row, 'addProblem')"
                      :disabled="!scope.row.isProblem"
                      >录入</el-button
                    >
                    <el-button
                      type="primary"
                      size="mini"
                      @click="getProblemList(scope.row)"
                      >查看</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
          <el-row
            style="padding-top: 20px; text-align: center"
            v-if="this.checkItemOptions.length > 0"
          >
            <el-button
              type="primary"
              style="margin-right: 20px"
              @click="addCheckTimes()"
              >确认提交</el-button
            >
            <el-button type="danger" @click="cancel2">取消并返回</el-button>
          </el-row>
        </el-col>
        <el-col
          :span="8"
          style="padding-left: 5px; text-align: center"
          v-if="this.checkItemOptions.length > 0"
        >
          <el-table :data="problemData" border max-height="400px">
            <el-table-column
              prop="checkRecordNo"
              label="问题记录编号"
              align="center"
              sortable
            ></el-table-column>
            <el-table-column label="操作" align="center" width="150px">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click="editProblem(scope.row, 'editProblem')"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteProblem(scope.row.checkRecordID)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </div>
    <service-dialog
      :show.sync="showDialog"
      :add-data="dataToDialog"
      @cancelDialog="cancelDialog"
      @submitDialog="submitDialog"
    ></service-dialog>
  </div>
</template>

<script>
import { GetCompany } from "../../../services/gettreedata.js";
import { GetDictionary } from "../../../services/cq_gettreedata.js";
import {
  GetTaskContent,
  GetCheckTable,
  GetProblems,
  DeleteProblem,
  AddCheckTimes,
} from "../../../services/personCenterTask.js";

import serviceDialog from "./serviceDialog";

export default {
  components: {
    serviceDialog,
  },
  data() {
    return {
      showDialog: false,
      submitReadonly: false,
      formData: {},
      checkCompanyList1: [],
      checkCompanyNameOptions1: [],
      checkContentsList: [],
      checkContentListOptions: [],
      checkItemOptions: [],
      checkItemOptionsCopy: [],
      dataToDialog: {},
      tableLoading: false,
      filterData: {},
      problemData: [],
      tast_content: [
        { type: "作业队", code: "0041" },
        { type: "专项检查", code: "0042" },
        { type: "关键环节", code: "0043" },
        { type: "重点要害部位及固定场所", code: "0046" },
        { type: "配属班组", code: "0047" },
      ],
      types: [],
      filterText: null,
    };
  },
  watch: {
    checkCompanyList1() {
      if (this.$refs.refHandle1) {
        this.$refs.refHandle1.dropDownVisible = false;
      }
    },
    checkContentsList() {
      if (this.$refs.refHandle2) {
        this.$refs.refHandle2.dropDownVisible = false;
      }
    },
  },
  mounted() {
    console.log(this.$route.params);
    this.formData = JSON.parse(JSON.stringify(this.$route.params));
    if (
      this.formData.taskList != "作业队" &&
      this.formData.taskList != "配属班组" &&
      this.formData.taskList != "重点要害部位及固定场所"
    ) {
      delete this.formData.companyCode;
    } else {
      this.checkCompanyList1 = this.dealCompanyCode(this.formData.companyCode);
    }
    this.handleGetCompany1();
    this.handleGetCheckList();
    this.getProblemType();
  },
  methods: {
    getDialogVdateReffect() {
      let date = new Date();
      let month =
        date.getMonth() < 9 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      let day = date.getDate() <= 9 ? "0" + date.getDate() : date.getDate();
      this.dataToDialog.verifyDate =
        date.getFullYear() + "-" + month + "-" + day;
      this.dataToDialog.rectEffect = "合格";
    },
    handleGetCompany1() {
      GetCompany()
        .then((res) => {
          this.checkCompanyNameOptions1 = res.data;
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    handleGetCheckList() {
      let code = this.tast_content.find(
        (item) => item.type === this.formData.taskList
      )["code"];
      GetTaskContent(code)
        .then((res) => {
          this.checkContentListOptions = res.data.childNodes;
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    generateChecklist() {
      if (this.checkContentsList.length === 0) {
        this.$message.error("请选择作业内容！");
      } else {
        this.formData.checkContentCode = this.checkContentsList[
          this.checkContentsList.length - 1
        ];
        GetCheckTable(this.formData.checkContentCode)
          .then((res) => {
            this.tableLoading = true;
            if (res.data.items.length === 0) {
              this.$message.error("该作业内容下无检查表，请检查后再选择！");
              return false;
            }
            this.submitReadonly = true;
            this.formData.checkItem = res.data.items[0].checkListItemName;
            this.checkItemOptions = res.data.items;
            this.checkItemOptionsCopy = res.data.items;
            this.tableLoading = false;
          })
          .catch((err) => {
            this.$message.error(err.message);
          });
      }
    },
    cancel1() {
      this.$router.go(-1);
    },
    handleClickTab(tab) {
      this.formData.checkItem = tab.label;
    },
    addCheckTimes() {
      this.$confirm("此操作将提交整个检查, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let addTimes = {
            supervisionTaskCode: this.formData.supervisionTaskCode,
            taskItem: this.formData.taskItem,
            supervisionTaskDetail2ID: this.formData.supervisionTaskDetail2ID,
          };
          console.log(addTimes);
          AddCheckTimes(addTimes)
            .then((res) => {
              this.$message({
                message: res.message,
                type: "success",
              });
              this.$router.go(-1);
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消提交",
          });
        });
    },
    cancel2() {
      this.submitReadonly = false;
      this.showDialog = false;
      this.checkItemOptions = [];
      this.checkContentsList = [];
      this.formData.checkContentCode = "";
      this.problemData = [];
    },
    addProblem(row, method) {
      this.dataToDialog = this.formData;
      this.dataToDialog.checkType = this.formData.type;
      this.dataToDialog.checkCompanyList = this.checkCompanyList1;
      this.dataToDialog.method = method;
      this.dataToDialog.immediately = "否";
      this.dataToDialog.education = "否";
      this.getDialogVdateReffect();
      Object.assign(this.dataToDialog, row);
      this.showDialog = true;
      console.log("addData", this.dataToDialog);
    },
    cancelDialog(val) {
      this.dataToDialog = {};
      this.showDialog = val;
    },
    submitDialog(val) {
      this.dataToDialog = {};
      this.showDialog = val;
    },
    getProblemList(row) {
      this.filterData.checkListID = row.checkListID;
      this.filterData.checkListItemCode = row.checkListItemCode;
      this.filterData.supervisionTaskCode = this.formData.supervisionTaskCode;
      this.filterData.supervisionTaskDetail2ID = this.formData.supervisionTaskDetail2ID;
      this.filterData.taskItem = this.formData.taskItem;
      this.filterData.recordStatus = "暂存";
      this.filterData.checkStaffID = this.formData.execStaffID;
      // console.log(JSON.stringify(this.filterData));
      GetProblems(this.filterData)
        .then((res) => {
          if (res.data.list.length === 0) {
            this.$message("此检查项下无暂存问题！");
          }
          this.problemData = res.data.list;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    editProblem(row, method) {
      this.dataToDialog = row;
      this.dataToDialog.method = method;
      this.dataToDialog.checkCompanyList = new Object(
        this.dealCompanyCode(row.companyCode)
      );
      if (this.dataToDialog.immediately == "否") this.getDialogVdateReffect();
      this.showDialog = true;
      console.log(this.dataToDialog);
    },
    dealCompanyCode(companyCode) {
      let checkCompanyList = [];
      let i = 0;
      while (i < companyCode.length) {
        checkCompanyList.push(companyCode.slice(0, i + 2));
        i = i + 2;
      }
      return checkCompanyList;
    },
    deleteProblem(id) {
      this.$confirm("此操作将删除此暂存问题, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          DeleteProblem(id)
            .then((res) => {
              this.$message({
                message: res.message,
                type: "success",
              });
              this.getProblemList(this.filterData);
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getProblemType() {
      GetDictionary({ name: "检查类型" })
        .then((res) => {
          this.types = res.data;
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
    onFilterText(val) {
      this.checkItemOptions = JSON.parse(
        JSON.stringify(this.checkItemOptionsCopy)
      );
      let ret = [];
      if (val) {
        if (this.checkItemOptions && this.checkItemOptions.length > 0) {
          this.checkItemOptions.forEach((v) => {
            let temp = {
              checkListID: v.checkListID,
              checkListItemCode: v.checkListItemCode,
              checkListItemName: v.checkListItemName,
              childNodes: [],
              insertDateCode: v.insertDateCode,
            };
            v.childNodes.forEach((v2) => {
              if (v2.checkListItemName.includes(val)) {
                temp.childNodes.push(v2);
              }
            });
            if (temp.childNodes.length > 0) {
              ret.push(temp);
            }
          });
          this.checkItemOptions = ret;
        } else {
          this.checkItemOptions = [];
        }
      }
    },
  },
};
</script>
<style>
.el-cascader-panel .el-radio {
  width: 100%;
  height: 100%;
  z-index: 10;
  position: absolute;
  top: 10px;
  right: 10px;
}
.el-cascader-panel .el-radio__input {
  visibility: hidden;
}
.el-cascader-panel .el-cascader-node__postfix {
  top: 10px;
}
</style>